package service.impl;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import model.User;
import service.IUserService;

import java.util.List;

/**
 * Created by ykj on 16/1/4.
 */
public class UserServiceImpl implements IUserService{
    public User login(String phone, String pwd){
        User user = User.dao.findFirst("select * from user where phone = ? and pwd = ?", phone, pwd);
        return user;
    }

    public User register(User user) {
        return null;
    }

    public Page findByPage(int page, int pageSize) {
        return User.dao.paginate(page, pageSize, "select * from User");
    }

    public Model save(Model model) {
        User user = (User) model;
        Long exists = Db.queryLong("select 1 from user where phone = ?", user.getPhone());
        //已存在相同记录
        if(exists != null) return null;
        boolean result = user.save();
        return result ? user : null;
    }

    public Model update(Model model) {
        User user = (User) model;
        Long exists = Db.queryLong("select 1 from user where id = ? and phone = ?", user.getId(), user.getPhone());
        //如果该id和phone不对应则不允许更新
        if(exists == null) return null;
        boolean result = user.update();
        return result ? user : null;
    }

    public boolean delete(int id) {
        return User.dao.deleteById(id);
    }


    public Model findById(int id) {
        return User.dao.findById(id);
    }

}
